package cn.bearspark.like.provider.service.impl;

import cn.bearspark.common.enumeration.LikedEnum;
import cn.bearspark.like.provider.dao.buffer.HappeningLikeUserIdPageListBuffer;
import cn.bearspark.like.provider.dao.buffer.HappeningLikeZSetBuffer;
import cn.bearspark.like.provider.dao.mapper.HappeningLikeMapper;
import cn.bearspark.like.provider.service.HappeningLikeService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author f
 */
@Service
public class HappeningLikeServiceImpl implements HappeningLikeService {

    private final HappeningLikeMapper happeningLikeMapper;

    private final HappeningLikeUserIdPageListBuffer happeningLikeUserIdPageListBuffer;
    private final HappeningLikeZSetBuffer happeningLikeZSetBuffer;

    public HappeningLikeServiceImpl(HappeningLikeMapper happeningLikeMapper,
                                    HappeningLikeUserIdPageListBuffer happeningLikeUserIdPageListBuffer,
                                    HappeningLikeZSetBuffer happeningLikeZSetBuffer) {
        this.happeningLikeMapper = happeningLikeMapper;
        this.happeningLikeUserIdPageListBuffer = happeningLikeUserIdPageListBuffer;
        this.happeningLikeZSetBuffer = happeningLikeZSetBuffer;
    }

    @Override
    public int likeHappening(long userId, long happeningId, int liked) {
        boolean isLiked = happeningLikeZSetBuffer.exists(happeningId, userId);

        int row;
        if (liked == LikedEnum.LIKED.getCode()) {
            // 如果用户点赞过该动态，则不能再次点赞
            if (isLiked) {
                return 0;
            }

            // 如果 liked 是点赞，则保存记录
            row = happeningLikeMapper.insert(userId, happeningId);
        } else {
            // 如果用户没有点赞过该动态，则不能取消点赞
            if (!isLiked) {
                return 0;
            }

            // 如果 liked 是未点赞，则删除记录
            row = happeningLikeMapper.delete(userId, happeningId);

            // 清理用户的点赞动态缓存
            happeningLikeZSetBuffer.clean(happeningId, userId);
        }

        // 删除动态的用户点赞列表的缓存
        happeningLikeUserIdPageListBuffer.clean(happeningId);

        return row;
    }

    @Override
    public List<Long> pageHappeningLikedUserId(int pageNum, int pageSize, long happeningId) {
        return happeningLikeUserIdPageListBuffer.page(happeningId, pageNum, pageSize);
    }

    @Override
    public Set<Long> getLikedHappeningIdSet(List<Long> happeningIdList, long userId) {
        return happeningLikeZSetBuffer.filter(happeningIdList, userId);
    }

    @Override
    public boolean isHappeningLiked(long happeningId, long userId) {
        return happeningLikeZSetBuffer.exists(happeningId, userId);
    }
}
